package com.tucc.hello.leetcode.no401_800.no401;

import java.util.*;

/**
 * @author tucc
 * @description todo
 * @package com.tucc.hello.leetcode
 * @date 2021/5/20
 **/
public class Solution {

    public static void main(String[] args) {
        Solution solution = new Solution();
        for(int i = 0;i <= 10;i ++){
            System.out.println(solution.readBinaryWatch(i));
        }
    }

    public static final int[] nums = {1, 2, 4, 8, 16, 32};

    public List<String> readBinaryWatch(int turnedOn) {
        List<String> result = new ArrayList<>();
        Map<Integer, Set<Integer>> map = new HashMap<>();
        for (int i = 0; i <= 6; i++) {
            map.put(i, readBinaryWatch2(i));
        }
        for (int i = 0; i <= 3; i++) {
            Set<Integer> left = map.get(i);
            if (left != null && left.size() > 0) {
                Set<Integer> right = map.get(turnedOn - i);
                if (right != null && right.size() > 0) {
                    for (Integer l : left) {
                        if (l <= 11) {
                            for (Integer r : right) {
                                if (r < 60) {
                                    result.add(l + ":" + (r < 10 ? "0" + r : r));
                                }
                            }
                        }
                    }
                }
            }
        }
        return result;
    }

    public Set<Integer> readBinaryWatch2(int turnedOn) {
        Set<Integer> result = new HashSet<>();
        readBinaryWatch(result, nums.length, turnedOn, 0);
        return result;
    }

    public void readBinaryWatch(Set<Integer> result, int size, int turnedOn, int val) {
        if (val < 60) {
            if (turnedOn == 0) {
                result.add(val);
            } else {
                for (int i = 0; i < size; i++) {
                    val += nums[i];
                    swap(i, size - 1);
                    readBinaryWatch(result, size - 1, turnedOn - 1, val);
                    swap(i, size - 1);
                    val -= nums[i];
                }
            }
        }
    }

    public void swap(int x, int y) {
        if (x != y) {
            int temp = nums[x];
            nums[x] = nums[y];
            nums[y] = temp;
        }
    }
}
